<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/28 00:40
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Car_Model extends WX_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 添加到购物车
     * @param $userid
     * @param $params
     * @return bool
     */
    public function addToCar($userid, $params)
    {
        $goodsId = $params['goodsId'];
        $num = $params['num'];
        $ruleId = $params['ruleId'];

        // 商品
        $goodsDb = clone($this->db);
        $q = $goodsDb->get_where('base_goods', ['id' => $goodsId, 'status' => 1]);
        $goods = $q->row_array();
        if (empty($goods)) {
            return false;
        }

        // rule
        $ruleDb = clone($this->db);
        $q = $ruleDb->get_where('base_goods_rule', ['id' => $ruleId]);
        $rule = $q->row_array();
        if (empty($rule)) {
            $this->setError('商品规格不存在');
            return false;
        }

        $stock = $rule['stock'];
        if ($stock < $num) {
            $this->setError('商品库存不足');
            return false;
        }

        $carDb = clone($this->db);
        $q = $carDb->get_where('user_car', ['userId' => $userid, 'goodsId' => $goodsId, 'ruleId' => $ruleId]);
        if ($q->row_array()) {
            if (isset($params['type']) && $params['type'] == 'buy') {
                $carDb->set('num', $num, true);
                $carDb->set('selected', 1, true);
            } else {
                $carDb->set('num', "num+{$num}", false);
            }
            $carDb->where(['userId' => $userid, 'goodsId' => $goodsId, 'ruleId' => $ruleId]);
            $carDb->update('user_car');
            if ($carDb->affected_rows()) {
                // modify selected
                if (isset($params['type']) && $params['type'] == 'buy') {
                    $this->_modifySelected($userid, $goodsId, $ruleId);
                }
                return true;
            }
        } else {
            // save to car
            $saveData = array(
                'userId' => $userid,
                'goodsId' => $goodsId,
                'ruleId' => $ruleId,
                'num' => $num,
                'created' => dateTime(),
                'selected' => 1
            );

            $db = clone($this->db);
            $db->insert('user_car', $saveData);
            if ($db->insert_id()) {
                // modify selected
                if (isset($params['type']) && $params['type'] == 'buy') {
                    $this->_modifySelected($userid, $goodsId, $ruleId);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * @param $userId
     * @param $goodsId
     * @param $ruleId
     * @return bool
     */
    public function _modifySelected($userId, $goodsId, $ruleId)
    {
        $db = clone($this->db);
        $db->where('userId', $userId);
        $db->where('selected', 1);
        $db->where('ruleId !=', $ruleId);
        $db->update('user_car', ['selected' => 0]);
        return true;
    }

    /**
     * 计算商品数量
     * @param $userid
     * @return mixed
     */
    public function num($userid)
    {
        $q = $this->db->select_sum('num')->get_where('user_car', ['userId' => $userid]);
        $row = $q->row_array();
        return $row['num'];
    }

    /**
     * 购物车列表
     * @param int $userId
     * @return array
     */
    public function getLists($userId = 0, $userType = 0, $selected = false)
    {

        $where = ['c.userId' => $userId];
        if ($selected) {
            $where = array_merge($where, ['c.selected' => 1]);
        }

        $db = clone($this->db);
        $q = $db->select('g.id as goodsId, g.baseId, g.goodsName, g.thumb, g.liveUrl, g.status, g.created, g.expType, g.expAmount, c.num,
            c.selected, r.id as ruleId, r.name as ruleName, r.stock, r.oldPrice, r.salePrice, r.purchaserPrice, r.expressWeight')
            ->from('user_car as c')
            ->join('base_goods as g', 'g.id = c.goodsId')
            ->join('base_goods_rule as r', 'r.id=c.ruleId')
            ->order_by('c.created', 'DESC')
            ->where($where)
            ->get();
        $rows = $q->result_array();

        if (empty($rows)) {
            return [];
        }

        $returns = array();
        foreach($rows as $item) {
            $price = $userType == 1 ? intval($item['purchaserPrice']) : intval($item['salePrice']);
            $returns[] = array(
                'goodsId' => intval($item['goodsId']),
                'baseId' => intval($item['baseId']),
                'goodsName' => $item['goodsName'],
                'thumb' => thumb($item['thumb'], 200, 200),
                'stock' => intval($item['stock']),
                'expType' => intval($item['expType']),
                'expAmount' => doubleval($item['expAmount']),
                'expressWeight' => doubleval($item['expressWeight']),
                'price' => $price,
                'price_cny' => money_format('%i', $price / 100),
                'status' => $item['status'] == 1 ? 'onSale' : 'offSale',
                'num' => intval($item['num']),
                'ruleName' => $item['ruleName'],
                'ruleId' => $item['ruleId'],
                'selected' => intval($item['selected'])
            );
        }

        return $returns;
    }

    /**
     * 修改商品
     * @param $userid
     * @param $goodsId
     * @param $status
     * @return mixed
     */
    public function modifySelect($userid, $goodsId, $status, $ruleId)
    {
        $db = clone($this->db);
        $db->where(['userId' => $userid, 'goodsId' => $goodsId, 'ruleId' => $ruleId]);
        $db->update('user_car', ['selected' => $status]);
        return $db->affected_rows();
    }

    /**
     * 改数量
     * @param $userid
     * @param $goodsId
     * @param $num
     * @return mixed
     */
    public function modifyNum($userid, $goodsId, $num)
    {
        $db = clone($this->db);
        $db->where(['userId' => $userid, 'goodsId' => $goodsId]);
        $db->update('user_car', ['num' => $num]);
        return $db->affected_rows();
    }

    /**
     * 修改
     * @param $userid
     * @param $type
     * @return mixed
     */
    public function modifyAll($userid, $type) {
        $db = clone($this->db);
        $db->where(['userId' => $userid]);

        if ($type == 'yes') {
            $db->update('user_car', ['selected' => 1]);
        } else {
            $db->update('user_car', ['selected' => 0]);
        }

        return $db->affected_rows();
    }

    /**
     * 删除行
     * @param $userid
     * @param $goodsId
     * @return mixed
     */
    public function deleteItem($userid, $goodsId)
    {
        $db = clone($this->db);
        $db->where(['userId' => $userid, 'goodsId' => $goodsId]);
        $db->delete('user_car');
        return $db->affected_rows();
    }

    /**
     * 获取商品数量
     * @param $userid
     * @return int
     */
    public function getCounter($userid)
    {
        $db = clone($this->db);
        $q = $db->select_sum('num')
            ->where(['userId' => $userid])
            ->get('user_car');
        $counter = $q->row_array();
        if (!empty($counter)) {
            return intval($counter['num']);
        }
        return 0;
    }
}